package ru.cybertek.dao.impl.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;

import ru.cybertek.domain.Person;

/**
 * @author Dmitry Demyankov
 * @version $Revision: 10 $
 * 
 *          (C) Copyright 2009 CyberTek Ltd. All rights reserved.
 */
public class SelectPersonByIdSqlQuery extends MappingSqlQuery
{
    public static final String SELECT_PERSON_BY_ID_SQL_QUERY = "SELECT id, "
        + "first_name, middle_name, last_name FROM person WHERE id = ?";

    public static final String PERSON_ID_COLUMN = "id";
    
    public static final String PERSON_FIRST_NAME_COLUMN = "first_name";
    
    public static final String PERSON_MIDDLE_NAME_COLUMN = "middle_name";
    
    public static final String PERSON_LAST_NAME_COLUMN = "last_name";
    
    /**
     * @param dataSource
     */
    public SelectPersonByIdSqlQuery(DataSource dataSource)
    {
        super(dataSource, SELECT_PERSON_BY_ID_SQL_QUERY);
        super.declareParameter(new SqlParameter("id", Types.INTEGER));
        compile();
    }
    
    /**
     * @param id
     * @return
     * @throws DataAccessException
     */
    public Person execute(Integer id) throws DataAccessException
    {
        if(id == null)
            return null;
        
        Person person = null;
        List result = super.execute(id.intValue());
        
        if(result != null && !result.isEmpty())
        {
            person = (Person)result.get(0);
        }
        
        return person;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.jdbc.object.MappingSqlQuery#mapRow(java.sql.ResultSet
     * , int)
     */
    @Override
    protected Person mapRow(ResultSet resultSet, int rowNum)
        throws SQLException
    {
        Person person = new Person();
        
        person.setId(resultSet.getInt(PERSON_ID_COLUMN));
        person.setFirstName(resultSet.getString(PERSON_FIRST_NAME_COLUMN));
        person.setMiddleName(resultSet.getString(PERSON_MIDDLE_NAME_COLUMN));
        person.setLastName(resultSet.getString(PERSON_LAST_NAME_COLUMN));
        
        return person;
    }
}
